// pages/withdrawCash/withdrawCash.js
var appData = getApp().globalData
var common = require("../../utils/Conmon.js");
Page({

  /**
   * 页面的初始数据
   */
  data: {
    index: 0,
    Bilvs: [],
    arrayObj: [],
    withdrawSets: [],
    LiveAmount: 0,
    Money: '',
    BankId: "0",
    TiMode: 0,
    Bili: 0,
    OnTimoney: 0,
    FeeVal: 0,   //单次提现手续费封顶值
    CssType: 'btn-custom'
  },
  bindPickerChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value);
    var that = this;
    that.bindChangeType(that.data.arrayObj[e.detail.value].id, that.data.arrayObj[e.detail.value].tiMode, that.data.arrayObj[e.detail.value].Bili, that.data.arrayObj[e.detail.value].onTimoney, that.data.arrayObj[e.detail.value].feeVal, that.data.arrayObj[e.detail.value].bankId);
    this.setData({
      index: e.detail.value
    })
  },

  /**
   * 拿到提现设置（判断是否开启）
   */
  bindGetWithdrawSet: function () {
    var that = this;
    that.setData({
      withdrawSets: [],
      arrayObj: [],
      Bilvs: []
    })
    wx.request({
      url: appData.apiurl + 'member/api/UserBankInfo/GetBankAndSets',
      method: 'GET',
      data: { custId: appData.custID, userId: wx.getStorageSync('UserInfo').UserID },
      header: {
        "content-type": "application/json",
        'X_ManuName': appData.manuName
      },
      success: function (res) {
        var len = that.data.withdrawSets;
        var banklen = that.data.arrayObj;
        var newbilvs = that.data.Bilvs;
        var strType = null;
        var bilv = '免费'
        wx.hideLoading()
        if (res.statusCode == 200 && res.data.code > 0) {
          var data = res.data.content;
          for (var i = 0; i < data.length; i++) {
            len.push(data[i])
            if (data[i].IsOpenFee == 1)
              bilv = data[i].FeeBili + '%';
            else
              bilv = '免费'

            for (var j = 0; j < data[i].TiModes.length; j++) {
              var str = data[i].TiModes[j];
              var bankId = '0';  //银行卡主键
              switch (str) {
                case "1":
                  if (data[i].UserBankInfo != null && data[i].UserBankInfo.length > 0) {
                    for (var k = 0; k < data[i].UserBankInfo.length; k++) {
                      var account = data[i].UserBankInfo[k].AliAccount;
                      if (account != null && account != undefined && account != "") {
                        if (bankId == "0")
                          bankId = data[i].UserBankInfo[k].ID;
                        else
                          bankId += "," + data[i].UserBankInfo[k].ID;
                      }
                    }
                  }
                  strType = { id: 0, name: '支付宝-提现手续费率(' + bilv + ')', icon: 'pay_icon02', tiMode: 1, Bili: data[i].FeeBili, onTimoney: data[i].OneTiMoney, feeVal: data[i].FeeVal, bankId: bankId };
                  newbilvs.push(bilv)
                  break;
                case "2":
                  strType = { id: 1, name: '微信-提现手续费率(' + bilv + ')', icon: 'pay_icon01', tiMode: 2, Bili: data[i].FeeBili, onTimoney: data[i].OneTiMoney, feeVal: data[i].FeeVal, bankId: bankId };
                  newbilvs.push(bilv)
                  break;
                case "3":
                  strType = { id: 2, name: '微信红包-提现手续费率(' + bilv + ')', icon: 'pay_icon03', tiMode: 3, Bili: data[i].FeeBili, onTimoney: data[i].OneTiMoney, feeVal: data[i].FeeVal, bankId: bankId };
                  newbilvs.push(bilv)
                  break;
                case "4":
                  if (data[i].UserBankInfo != null && data[i].UserBankInfo.length > 0) {
                    for (var k = 0; k < data[i].UserBankInfo.length; k++) {
                      var bankNo = data[i].UserBankInfo[k].BankNo;
                      if (bankNo != null && bankNo != undefined && bankNo != "") {
                        if (bankId == "0")
                          bankId = data[i].UserBankInfo[k].ID;
                        else
                          bankId += "," + data[i].UserBankInfo[k].ID;
                      }
                    }
                  }
                  strType = { id: 3, name: '银行卡-提现手续费率(' + bilv + ')', icon: 'pay_icon03', tiMode: 4, Bili: data[i].FeeBili, onTimoney: data[i].OneTiMoney, feeVal: data[i].FeeVal, bankId: bankId };
                  newbilvs.push(bilv)
                  break;
              }
              if (strType != null)
                banklen.push(strType)
            }
          }
          var _index = 0;
          if (banklen.length > 0) {
            for (var f = 0; f < banklen.length; f++) {
              if (banklen[f].id == that.data.newIndex) {
                _index = f;
              }
            }
          }
          that.setData({
            withdrawSets: len,
            arrayObj: banklen,
            Bilvs: newbilvs,
            index: _index
          })

          that.bindChangeType(that.data.arrayObj[that.data.index].id, that.data.arrayObj[that.data.index].tiMode, that.data.arrayObj[that.data.index].Bili, that.data.arrayObj[that.data.index].onTimoney, that.data.arrayObj[that.data.index].feeVal, that.data.arrayObj[that.data.index].bankId);
          //that.bindGetBankCard();
          console.log(res.data)
        } else {
          wx.hideLoading()
          wx.showModal({ title: '错误', content: '请求错误', showCancel: false })
        }
      },
      fail: function (res) {
        wx.hideLoading()
        wx.showModal({ title: '错误', content: '请求获取异常错误', showCancel: false })
        console.log(res.data)
      }
    })
  },
  /**
   * 获取可提现金额
   */
  bindGetLiveAmount: function () {
    var that = this;
    wx.request({
      url: appData.apiurl + 'member/api/currencyinfo/getuserdifference',
      method: 'GET',
      data: { custId: appData.custID, userId: wx.getStorageSync('UserInfo').UserID, type: 6 },
      header: {
        "content-type": "application/json",
        'X_ManuName': appData.manuName
      },
      success: function (res) {
        if (res.statusCode == 200 && res.data.code > 0) {
          var money = res.data.content.LiveAmount;
          that.setData({
            LiveAmount: money
          })
          console.log(res.data)
        } else {
          that.setData({
            LiveAmount: 0
          })
        }
      },
      fail: function (res) {
        wx.showModal({ title: '错误', content: '请求获取异常错误', showCancel: false })
        console.log(res.data)
      }
    })
  },

  //选择提现类型
  bindChangeType: function (id, tiMode, bili, onTimoney, feeVal, bankId) {
    var that = this;
    var bool = false;
    //请求获取银行卡账号，如果没有银行卡  则完善资料
    if (tiMode == 1 || tiMode == 4) {
      if (bankId == '0')
        bool = true;
    }
    that.setData({
      BankId: bankId,
      TiMode: tiMode,
      Bili: bili,
      OnTimoney: onTimoney,
      FeeVal: feeVal,
      Money: '',
      CssType: 'btn-custom'
    })

    if (bool) {
      var index1 = tiMode == 4 ? 2 : 1;
      var index2 = tiMode == 4 ? 1 : 0;
      wx.showModal({
        title: '提示',
        content: tiMode == 1 ? '请先完善支付宝信息' : '请先完善银行卡信息',
        showCancel: false,
        success: function (res) {
          if (res.confirm) {
            wx.redirectTo({
              url: '/pages/withdrawal/withdrawal?bankId=0&type=' + index1 + '&soure=1&Index=' + index2,
            })
            console.log('用户点击确定')
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
    }
  },

  /**
   * 绑定输入提现金额事件
   */
  bindMoneyInput: function (e) {
    var that = this;
    var money = e.detail.value;
    var yue = that.data.LiveAmount;
    var css = 'btn-custom';
    if (Number(money) < 0 || money == '') {
      money = '';
      css = 'btn-custom';
    } else if (Number(money) > Number(yue)) {
      money = yue;
      if (Number(yue) <= 0)
        css = 'btn-custom';
      else
        css = 'btn-primary';
    }
    else if (Number(money) > 0 && Number(money) <= Number(yue)) {
      css = 'btn-primary';
    }

    that.setData({
      Money: money,
      CssType: css
    })
  },

  /**
   * 确定提现
   */
  BindSureClickTap: function (e) {
    var that = this;
    var tiMoney = Number(that.data.Money);
    var yue = Number(that.data.LiveAmount);
    var onTimoney = Number(that.data.OnTimoney);
    var tiMode = that.data.TiMode;
    var bankId = that.data.BankId+"";

    if (that.data.CssType == 'btn-custom') {
      return;
    }
    if (onTimoney > 0 && onTimoney != '') {
      if (tiMoney < onTimoney) {
        wx.showModal({ title: '警告', content: '一次性提取不能小于[' + onTimoney + '元]', showCancel: false })
        return;
      }
    }
    var _bankId = '0';
    if (that.data.Type == tiMode) {
      _bankId = that.data.newbankId.split(',');
    } else {
      _bankId = bankId.split(',');
    }
    if (_bankId.length > 1) {
      if (tiMode == "1") {
        wx.showModal({
          title: '警告', content: '您绑定了多个支付宝', success: function (res) {
            if (res.confirm) {
              wx.redirectTo({
                url: '/pages/bankCardList/bankCardList?type=1&soure=1',
              })
            }
          }
        })
        return;
      }
      if (tiMode == "4" || tiMode == "5") {
        wx.showModal({
          title: '警告', content: '您绑定了多张银行卡', success: function (res) {
            if (res.confirm) {
              wx.redirectTo({
                url: '/pages/bankCardList/bankCardList?type=2&soure=1',
              })
            }
          }
        })
        return;
      }
    } else if (_bankId.length == 1 && _bankId[0] == "0") {
      if (tiMode == "1") {
        wx.showModal({
          title: '警告', content: '请先完善支付宝信息', success: function (res) {
            if (res.confirm) {
              wx.redirectTo({
                url: '/pages/bankCardList/bankCardList?type=1&soure=1',
              })
            }
          }
        })
        return;
      }
      if (tiMode == "4" || tiMode == "5") {
        wx.showModal({
          title: '警告', content: '请先完善银行卡信息', success: function (res) {
            if (res.confirm) {
              wx.redirectTo({
                url: '/pages/bankCardList/bankCardList?type=2&soure=1',
              })
            }
          }
        })
        return;
      }

    }

    var url;
    //提交提现金额
    wx.showLoading({ title: '提现中...', mask: true });
    wx.request({
      url: appData.apiurl + 'member/api/WithdrawalsList/Withdrawals',
      method: 'GET',
      data: { custid: appData.custID, userId: wx.getStorageSync('UserInfo').UserID, tiMode: tiMode, bankId: _bankId[0], tiMoney: tiMoney },
      header: {
        "content-type": "application/json",
        'X_ManuName': appData.manuName
      },
      success: function (res) {
        wx.hideLoading()
        if (res.data.code > 0) {
          if (res.data.content.Item1 == 0) {
            wx.showModal({ title: '错误', content: '提取金额需要大于0', showCancel: false })
          } else if (res.data.content.Item1 == -1) {
            wx.showModal({ title: '错误', content: '余额不足', showCancel: false })
          } else if (res.data.content.Item1 == -2) {
            wx.showModal({ title: '错误', content: "日提现最高额度不能超过‘" + res.data.content.Item3 + "’元", showCancel: false })
          } else if (res.data.content.Item1 == -3) {
            wx.showModal({ title: '错误', content: "周提现最高额度不能超过‘" + res.data.content.Item3 + "’元", showCancel: false })
          } else if (res.data.content.Item1 == -4) {
            wx.showModal({ title: '错误', content: "月提现最高额度不能超过‘" + res.data.content.Item3 + "’元", showCancel: false })
          } else if (res.data.content.Item1 == -10) {
            url = '/pages/withdrawCashFail/withdrawCashFail';
          } else {
            //提现成功
            url = '/pages/withdrawCashSucceed/withdrawCashSucceed?timoney=' + res.data.content.Item2 + '&feilvMoney=' + res.data.content.Item3;
          }
        } else {
          wx.showModal({ title: '错误', content: '请求错误', showCancel: false })
        }
      },
      fail: function (res) {
        wx.hideLoading()
        wx.showModal({ title: '错误', content: '请求获取异常错误', showCancel: false })
        console.log(res.data)
      },

      complete: function (res) {
        if (url != null && url != undefined) {
          wx.redirectTo({
            url: url,
          })
        }
      }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    common.pageInit( function () {
    });
    var that = this;
    var _type = options.type;
    var _bankId = options.bankId;

    if (_bankId != undefined && _bankId != null) {
      that.setData({
        newbankId: _bankId
      })
    }
    var num = 0;
    var newType = 0;
    if (_type != undefined && _type != null) {
      num = _type;
      newType = _type;
      if (_type == 2) {
        num = 3;
        newType = 4;
      } else if (_type == 1) {
        num = 0;
      }
    }
    that.setData({
      Type: newType,
      newIndex: num,
      newbankId: _bankId
    })
    wx.showLoading({ title: '加载中...', mask: true });
    this.bindGetLiveAmount()
    this.bindGetWithdrawSet();
  },


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})